using System;
using System.Collections.Generic;
using System.Text;
using WindowsLive.Writer.Api;
using System.Windows.Forms;
using PluginSurrogate;
using System.IO;
using System.Reflection;
using System.Diagnostics;

namespace InsertFromSkyDrive
{
    [WriterPlugin("8fd59d59-9c4e-487c-8df0-50f18a09d73d", "InsertFromSkyDrive",
        Description = "Description",
        HasEditableOptions = true,
        Name = "Insert From SkyDrive",
        PublisherUrl = "http://scottisafooldev.spaces.live.com",
        ImagePath = "icon.gif")]
    [InsertableContentSource("SkyDrive Embed")]

    public class SkyDrive : ContentSource
    {
        IProperties m_default;

        public override void Initialize(IProperties pluginOptions)
        {
            base.Initialize(pluginOptions);
            m_default = pluginOptions;
        }

        public override DialogResult CreateContent(IWin32Window dialogOwner, ref string newContent)
        {
            string exePath = GetExePath();

            CreateContentData output = (CreateContentData) SurrogateHelper.ExecuteModally(
                dialogOwner,
                new CreateContentData { Settings = new PluginSettings(m_default), Content = newContent },
                exePath,
                "CreateContent " + CommandLineEscape(GetWriterDirectory()));

            if (output == null)
                return DialogResult.Cancel;

            output.Settings.Save(m_default);

            if (output.Content == null)
                return DialogResult.Cancel;

            newContent = output.Content;
            return DialogResult.OK;
        }

        public override void EditOptions(IWin32Window dialogOwner)
        {
            string exePath = GetExePath();

            PluginSettings settings = (PluginSettings) SurrogateHelper.ExecuteModally(
                dialogOwner,
                new PluginSettings(this.Options),
                exePath,
                "Options " + CommandLineEscape(GetWriterDirectory()));

            settings.Save(this.Options);
        }

        private static string GetExePath()
        {
            string exePath = Path.Combine(
                Path.GetDirectoryName(typeof(SkyDrive).Assembly.Location),
                "InsertFromSkyDriveProc.exe");

            if (!File.Exists(exePath))
                throw new ApplicationException("Missing component:\r\n\r\n" + exePath);
            return exePath;
        }

        private static string GetWriterDirectory()
        {
            return AppDomain.CurrentDomain.BaseDirectory;
        }

        private static string CommandLineEscape(string str)
        {
            return str.Replace("\\", "\\\\");
        }
    }

    [Serializable]
    public class CreateContentData
    {
        public PluginSettings Settings;
        public string Content;
    }
}
